package com.sxfq.loansupermarket.backsystem.modular.logsf.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ScoreDealInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.CheckoutMethodInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.DoctorInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServicedInfo;
import com.sxfq.loansupermarket.backsystem.modular.logsf.entity.DiscountAudit;
import com.sxfq.loansupermarket.backsystem.modular.logsf.service.IDiscountExamineService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import javax.validation.Valid;
import java.util.List;

/**
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/discountAudit")
public class DiscountExamineController extends BaseController {
    @Autowired
    IDiscountExamineService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    ICustomerService customerService;

    private String PREFIX = "/logsf/discountExamine/";

    //折扣列表
    @RequestMapping(value = "/discountAudit_index")
    public String jumpDiscountAuditIndex(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("outParientName", ShiroKit.getUser().getOutpatientName());
        model.addAttribute("auditNode", redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"AuditNode",0));
        model.addAttribute("deptName", redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"DeptName",0));
        return PREFIX + "discountToExamine.html";
    }

    /**
     * 折扣审核列表
     */
    @RequestMapping("/discountAuditList")
    @ResponseBody
    public Object discountAuditList(DiscountAudit info, HttpServletRequest request) {
        Page<DiscountAudit> page = new PageFactory<DiscountAudit>().defaultPage();
        info.setUserDept(ShiroKit.getUser().getOutpatientName());
        info.setAuditNode(Integer.parseInt(redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"AuditNode",0)+""));
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<DiscountAudit> list = service.getList(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.getList(page, info);
            }
            page.setRecords(list);
            page.setTotal(service.getQueryPagesCount(page, info));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 獲取統計數量
     */
    @RequestMapping(value = "/getCount", method = RequestMethod.POST)
    @ResponseBody
    public List<TongJiInfo> getCount(DiscountAudit info, HttpServletRequest request) {
        return service.getQueryPagesCounts(info);
    }

    /**
     * 修改项目
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/discountAudit_toExamine/{id}/{reservationsId}/{customerId}/{operationTime}/{outPatientName}/{status}/{discount}")
    public String discountAuditTooExamine(@PathVariable("id") String id, @PathVariable("reservationsId") String reservationsId, @PathVariable("customerId") String customerId,
                                          @PathVariable("operationTime") String operationTime, @PathVariable("outPatientName") String outPatientName, @PathVariable("status") String status, @PathVariable("discount") Double discount,
                                          Model model) {
        String tableHeadsql = "select id,abbreviation from dept where simplename='" + outPatientName + "'";
        Dept dept = sqlMapper.selectOne(tableHeadsql, Dept.class);
        String tableName = dept.getAbbreviation() + "deal_info";
        String tableName1 = dept.getAbbreviation() + "customer_info";
        String sql = "select * from " + tableName + " t left join "+redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"pay_service_info",0)+" t1 on t.pay_service_id = t1.id where t.reservations_id = '" + reservationsId + "' and t.operation_time = '" + operationTime + "'";
        List<PayServicedInfo> dealInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        if (redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"DoctorInfoList",0)== null) {
            String doctorListSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                    " where b.abbreviation='" + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"" + "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
            List<DoctorInfo> doctorInfoList = sqlMapper.selectList(doctorListSql, DoctorInfo.class);
            redisTemplate.opsForList().leftPush(ShiroKit.getUser().getAccount()+"DoctorInfoList",doctorInfoList);
        }
        model.addAttribute("doctorList", redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"DoctorInfoList",0));
        String getcutomersql = "select customer_name,customer_age,(CASE customer_sex" +
                "  WHEN 1 THEN  " +
                "  '男' " +
                "  WHEN 2 THEN " +
                "  '女' " +
                "  ELSE  " +
                "  '未知'  " +
                "  END   " +
                " ) as sex ,customer_phone,medical_record_number,field_tc,jfbalance,money_balance," +
                " treatment_unit from " + tableName1 + " t2 where id= '" + customerId + "';";
        CustomerInfo customerInfo = sqlMapper.selectOne(getcutomersql, CustomerInfo.class);
        //获取抵扣方式
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')";
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        Double totalSum1 = 0.00;
        Double realTotalSum = 0.00;
        String isDeduction = "0";
        String isDeposit = "0";
        Double originalPrice = 0.00;
        Double totalArrears = 0.00;
        Double newTotalSum = 0.00;
        if (dealInfoList.size() > 0) {
            for (int i = 0; i < dealInfoList.size(); i++) {
                totalSum1 += dealInfoList.get(i).getFoldingPay();
                realTotalSum += dealInfoList.get(i).getServiceActualPay();
                originalPrice += dealInfoList.get(i).getPrimaryAmount();
                totalArrears += dealInfoList.get(i).getArrears();
                newTotalSum = newTotalSum + dealInfoList.get(i).getFoldingPay() - dealInfoList.get(i).getDeductionAmount() - dealInfoList.get(i).getDepositAmount();
                if (dealInfoList.get(i).getDeductionAmount() > 0) {
                    isDeduction = "1";
                }
                if (dealInfoList.get(i).getDepositAmount() > 0) {
                    isDeposit = "1";
                }
            }
            String discountSql = "select id,discount_grade from t_discount_audit where id = '" + id + "'";
            DiscountAudit discountAudit = sqlMapper.selectOne(discountSql, DiscountAudit.class);
            model.addAttribute("dealInfoList", dealInfoList);
            model.addAttribute("totalDiscount", dealInfoList.get(0).getWholeDiscount());
            model.addAttribute("customerId", customerId);
            model.addAttribute("reservationsId", reservationsId);
            model.addAttribute("checkoutMethodHtml", checkoutMethodHtml);
            model.addAttribute("newTotalSum", newTotalSum);
            model.addAttribute("originalPrice", originalPrice);
            model.addAttribute("isDeduction", isDeduction);
            model.addAttribute("isDeposit", isDeposit);
            model.addAttribute("totalArrears", totalArrears);
            model.addAttribute("operationTime", operationTime);
            model.addAttribute("checkoutMethodList", checkoutMethodList);
            model.addAttribute("totalSum1", totalSum1);
            model.addAttribute("realTotalSum", realTotalSum);
            model.addAttribute("id", id);
            model.addAttribute("discount", discount);
            model.addAttribute("discountGrade", discountAudit.getDiscountGrade());
            model.addAttribute("status", status);
            String jfbalancesql="select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='"+customerInfo.getReservationsId()+"'";
            ScoreDealInfo scoreDealInfo=sqlMapper.selectOne(jfbalancesql,ScoreDealInfo.class);
            BigDecimal b1 = new BigDecimal(Double.parseDouble(redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Proportional",0)+""));
            BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
            customerInfo.setJfbalance(b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            model.addAttribute("customerInfo", customerInfo);
            model.addAttribute("treatmentUnit", customerInfo.getTreatmentUnit());
            return PREFIX + "discountExamine_detail.html";
        } else {
            String delesql = "delete from t_discount_audit where reservations_id = '" + reservationsId + "' and operation_time = '" + operationTime + "'";
            sqlMapper.delete(delesql);
            return "/tDiscountAuditClose.html";
        }
    }

    /**
     * 修改项目
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/discountAudit_toExamines/{id}/{reservationsId}/{customerId}/{operationTime}/{outPatientName}/{status}/{discount}")
    public String discountAuditTooExamines(@PathVariable("id") String id, @PathVariable("reservationsId") String reservationsId, @PathVariable("customerId") String customerId,
                                          @PathVariable("operationTime") String operationTime, @PathVariable("outPatientName") String outPatientName, @PathVariable("status") String status, @PathVariable("discount") Double discount,
                                          Model model) {
        String tableHeadsql = "select id,abbreviation from dept where simplename='" + outPatientName + "'";
        Dept dept = sqlMapper.selectOne(tableHeadsql, Dept.class);
        String tableName = dept.getAbbreviation() + "deal_info";
        String tableName1 = dept.getAbbreviation() + "customer_info";
        String sql = "select * from " + tableName + " t left join "+redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"pay_service_info",0)+" t1 on t.pay_service_id = t1.id where t.reservations_id = '" + reservationsId + "' and t.operation_time = '" + operationTime + "'";
        List<PayServicedInfo> dealInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        String docSql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + dept.getAbbreviation() + "' and (c.name='医生' or c.name='洁牙师')";
        List<ConsultantInfo> doctorList = sqlMapper.selectList(docSql, ConsultantInfo.class);
        String getcutomersql = "select customer_name,customer_age,(CASE customer_sex" +
                "  WHEN 1 THEN  " +
                "  '男' " +
                "  WHEN 2 THEN " +
                "  '女' " +
                "  ELSE  " +
                "  '未知'  " +
                "  END   " +
                " ) as sex ,customer_phone,medical_record_number,field_tc,jfbalance,money_balance," +
                " treatment_unit from " + tableName1 + " t2 where id= '" + customerId + "';";
        CustomerInfo customerInfo = sqlMapper.selectOne(getcutomersql, CustomerInfo.class);
        //获取抵扣方式
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')";
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        Double totalSum1 = 0.00;
        Double realTotalSum = 0.00;
        String isDeduction = "0";
        String isDeposit = "0";
        Double originalPrice = 0.00;
        Double totalArrears = 0.00;
        Double newTotalSum = 0.00;
        if (dealInfoList.size() > 0) {
            for (int i = 0; i < dealInfoList.size(); i++) {
                totalSum1 += dealInfoList.get(i).getFoldingPay();
                realTotalSum += dealInfoList.get(i).getServiceActualPay();
                originalPrice += dealInfoList.get(i).getPrimaryAmount();
                totalArrears += dealInfoList.get(i).getArrears();
                newTotalSum = newTotalSum + dealInfoList.get(i).getFoldingPay() - dealInfoList.get(i).getDeductionAmount() - dealInfoList.get(i).getDepositAmount();
                if (dealInfoList.get(i).getDeductionAmount() > 0) {
                    isDeduction = "1";
                }
                if (dealInfoList.get(i).getDepositAmount() > 0) {
                    isDeposit = "1";
                }
            }
            String discountSql = "select id,discount_grade from t_discount_audit where id = '" + id + "'";
            DiscountAudit discountAudit = sqlMapper.selectOne(discountSql, DiscountAudit.class);
            model.addAttribute("dealInfoList", dealInfoList);
            model.addAttribute("totalDiscount", dealInfoList.get(0).getWholeDiscount());
            model.addAttribute("customerId", customerId);
            model.addAttribute("reservationsId", reservationsId);
            model.addAttribute("checkoutMethodHtml", checkoutMethodHtml);
            model.addAttribute("doctorList", doctorList);
            model.addAttribute("newTotalSum", newTotalSum);
            model.addAttribute("originalPrice", originalPrice);
            model.addAttribute("isDeduction", isDeduction);
            model.addAttribute("isDeposit", isDeposit);
            model.addAttribute("totalArrears", totalArrears);
            model.addAttribute("operationTime", operationTime);
            model.addAttribute("checkoutMethodList", checkoutMethodList);
            model.addAttribute("totalSum1", totalSum1);
            model.addAttribute("realTotalSum", realTotalSum);
            model.addAttribute("id", id);
            model.addAttribute("discount", discount);
            model.addAttribute("discountGrade", discountAudit.getDiscountGrade());
            model.addAttribute("status", status);
            String jfbalancesql="select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='"+customerInfo.getReservationsId()+"'";
            ScoreDealInfo scoreDealInfo=sqlMapper.selectOne(jfbalancesql,ScoreDealInfo.class);
            BigDecimal b1 = new BigDecimal(Double.parseDouble(redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Proportional",0)+""));
            BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
            customerInfo.setJfbalance(b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            model.addAttribute("customerInfo", customerInfo);
            model.addAttribute("treatmentUnit", customerInfo.getTreatmentUnit());
            return PREFIX + "discountExamine_details.html";
        } else {
            String delesql = "delete from t_discount_audit where reservations_id = '" + reservationsId + "' and operation_time = '" + operationTime + "'";
            sqlMapper.delete(delesql);
            return "/tDiscountAuditClose.html";
        }
    }


    //修改开单项目提交
    @RequestMapping(value = "/updateAuditStatus")
    @ResponseBody
    public int updateAuditStatus(@Valid DiscountAudit discountAudit, HttpServletRequest request) {
        return service.updateAuditStatus(discountAudit);
    }

    //修改开单项目提交
    @RequestMapping(value = "/auditFailed")
    @ResponseBody
    public int auditFailed(@Valid DiscountAudit discountAudit, HttpServletRequest request) {
        return service.auditFailed(discountAudit);
    }
}